import React, { useEffect, useMemo, useState } from 'react'
import {View, Button,Image,Text} from '@tarojs/components'
import Taro, { useDidShow } from '@tarojs/taro'
import { AtActionSheet } from 'taro-ui'
import InputNumber from '@/components/InputNumber'

import './index.less'
import "taro-ui/dist/style/components/action-sheet.scss";
import { throttle,RoundNum } from '@/utils/Tools'

export default function OrderOptions() {
  const [info,setInfo] = useState({})
  const [active, setactive] = useState(null)
  const [PopupService, setPopupService] = useState(false)

  useEffect(()=>{
    Taro.showLoading({title:'加载中...'})
    Taro.$get(`/act/activities/area/${Taro.getCurrentInstance().router.params.id}`,'','1').then(res=>{
      setInfo(res.content)
      let value = res.content.areaList.findIndex(res=>res.inventory>0)
      setactive(value>=0?value:null)
    })
  },[])


  function handleTabs(e){  /// 切换选项
    if(info.areaList[e].inventory){
      setactive(e)
    }
  }
  const handleSubmit = throttle(async ()=>{
    const data = {
      activityId:info.id,
      areaId:info.areaList[active].id,
      areaQuantity:info.areaList[active].ticketNum || 1
    }
    const res = await Taro.$post('/act/orders/create',data,1)
    if(res.code == '1'){
      Taro.navigateTo({
        url:`/orderSubPack/order-confirm/index?orderId=${res.content.orderId}`
      })
    }else{
      Taro.$toast(res.message || '提交失败')
    }
  },3000)
  function changeValue(e,data){   //  免费票票数
    if(data > 0 || data === 0){
      const arr = [...info.areaList]
      arr[data].ticketNum = e
      setInfo({...info,areaList:arr})
    }
  }

  const calcPrice = useMemo(()=>{
    if(!(active>0||active==0)) return 0
    return RoundNum(info.areaList[active].price*(info.areaList[active].ticketNum || 1))
  },[active,info])
  return (
  info.id?
  <View className="order-confirm">
    <View className="confirm-header">
      <Image className="header-img" src={Taro.getMedia(info.logo)} mode="aspectFill"></Image>
      <View className="header-info">
        <View className="dot2 h2">{info.title}</View>
        <View className='p'>{info.dateStr} </View>
        <View className='p'>{info.locationName}</View>
        {active>=0?<View className='p'>{info.areaList[active]?.ticketNum || 1}张 {info.areaList[active]?.name} 原价¥{calcPrice}</View>:null}
      </View>
      <View className="confirm-service" onClick={()=>{setPopupService(true)}}>
        <View className='p'><Image className="img" src={require('@/static/check.svg')}></Image>限时退票</View>
        <View className='p'><Image className="img" src={require('@/static/check.svg')}></Image>电子票入场</View>
        <View className="service-span">服务须知 <Text className='at-icon at-icon-chevron-right' style="color:#26282A;font-size:15px"></Text></View>
      </View>
    </View>
    <AtActionSheet isOpened={PopupService} onClose={()=>{setPopupService(false)}}>
      <View className="popup-service">
        <View className="service-header">
          <View className='h2'>服务须知</View>
          <Image onClick={()=>{setPopupService(false)}} src={require('@/static/close.png')} className="header-close"></Image>
        </View>
        <View className="service-list">
          <View className="list-item">
            <Image src={require('@/static/check.svg')} className="item-img"></Image>
            <View className='p'>限时退票</View>
            该活动支持退票，退票需要收取手续费，具体规则如下：
            <View className="item-table">
              <View className="table-header table-main"><Text>申请退票时间段</Text><Text>退票手续费</Text></View>
              <View className="table-body table-main">
                {info.refundRule?.map((res,idx)=>{
                  return <View key={res.timeSlot} className={`body-item ${info.refundRule.findIndex(ret=>ret.selected)>idx?'gary':''}`}><Text>{res.timeSlot}{res.selected?<Text className='item-cur'>当前阶段</Text>:null}</Text><Text>{res.refundServiceCharge}</Text></View>
                })}
              </View>
            </View>
          </View>
          <View className="list-item">
            <Image src={require('@/static/check.svg')} className="item-img"></Image>
            <View className='p'>电子票进场</View>
            在”我的-我的订单”查看订单详情，通过二维码检票进场。
          </View>
        </View>
      </View>
    </AtActionSheet>
    <View className="confirm-intro">
      <View className='h2'>票档</View>
      <View className="intro-list">
        {info.areaList?.map((item,index)=>{
          return <View className={`intro-item ${active === index?'active':''} ${item.inventory == 0?'disabled':''}`} key={item.id} onClick={()=>{handleTabs(index)}}>
          <View className="item-title">
            <View className='h3'>{item.name} {item.inventory == 0?<>(已售罄)</>:null}</View>
          </View>
          <View className="item-price">
            {item.price>0?<Text style="font-size: 20rpx;">¥</Text>:null}
            {item.price>0?item.price:'免费'} 
            {active === index && item.inventory &&  item.inventory < 10?<View className="price-num">仅剩{item.inventory}张</View>:null}
          </View>
        </View>
        })}
      </View>
      <View className="intro-footer">
        <View className="footer-h3">购票数量</View>
        <View style={{marginLeft:8,marginRight:'auto'}}>余票 <Text className='theme-color'>{info.areaList[active]?.inventory || 0}</Text> 张</View>
        <InputNumber value={info.areaList[active]?.ticketNum || 1} maxValue={info.areaList[active]?.purchaseQuantity || 1} onCut={(e)=>{
          let value = info.areaList[active]?.ticketNum || 1
          value > 0? value-- : value = 1
          changeValue(value,active)
        }} onAdd={(e)=>{
          let value = info.areaList[active]?.ticketNum || 1
          value >= 0? value++ : value = 1
          changeValue(value,active)
        }} />
      </View>
    </View>

    <View className="confirm-button">
      <View className="button-info">
        <View className='h5'>应付 <Text className='theme-color' style="font-size: 20rpx;margin-left: 10rpx;">￥</Text> <Text className='theme-color' style="font-size: 36rpx; font-weight: 700;">{calcPrice}</Text></View>
      </View>
      <Button className='button' onClick={()=>{handleSubmit()}}>立即付款</Button>
    </View>
  </View>:null
  )
}
